package org.mspring.mlog.action.admin;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.entity.Node;
import org.mspring.mlog.entity.User;
import org.mspring.mlog.entity.em.NodeType;
import org.mspring.mlog.security.SecurityService;
import org.mspring.mlog.security.service.NodeService;
import org.mspring.nbee.common.utils.RequestUtils;
import org.mspring.nbee.web.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Gao Youbo
 * @since 2014年10月21日
 */
@Action
@RequestMapping("/admin")
public class RedirectAction extends BaseAdminAction {

    private SecurityService securityService;
    private NodeService nodeService;

    @RequestMapping("/redirect")
    public String redirect(HttpServletRequest request, HttpServletResponse response, Model model) {
        String id = RequestUtils.getParam(request, "id");
        if (StringUtils.isBlank(id)) {
            // return prompt(model, "未找到该页面");
        }
        Node node = nodeService.findById(id);
        User user = securityService.getCurrentUser(request);
        List<Node> tabs = null;
        Node openTab = null;
        String url = "";
        if (node.getType().equals(NodeType.TREE_ITEM)) {
            tabs = nodeService.listTabByUser(node.getId(), user.getId());
            if (tabs == null || tabs.isEmpty()) {
                if (StringUtils.isBlank(url)) {
                    // return prompt(model, "<font color=red>&lt;" +
                    // item.getName() + "&gt;</font> 未找到，或您无权访问该页面");
                }
            }
            if (tabs.isEmpty()) {
                openTab = tabs.get(0);
            } else {
                openTab = nodeService.getOpenTab(node.getId(), user.getId());
            }
            url = openTab.getUrl();
        } else if (node.getType().equals(NodeType.TAB)) {
            url = node.getUrl();
            openTab = node;
            tabs = nodeService.listTabByUser(openTab.getParent(), user.getId());
        }

        if (StringUtils.isBlank(url)) {
            // return prompt(model, "<font color=red>&lt;" + item.getName() +
            // "&gt;</font> 未找到，或您无权访问该页面");
        }
        model.addAttribute("tabs", tabs);
        model.addAttribute("openTab", openTab);
        return "/admin/redirect";
    }

    @Autowired
    public void setSecurityService(SecurityService securityService) {
        this.securityService = securityService;
    }

    @Autowired
    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

}
